package com.example.myapplication.module

import android.app.Activity
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import com.example.myapplication.entity.CloudBean
import com.example.myapplication.module.adapter.CloudAdapter
import com.example.mylibrary.adapter.BaseRecyclerAdapter
import com.example.mylibrary.utils.UiTools
import com.example.mylibrary.utils.UiTools.getDeviceWidth

class ChoosePopup(var activity: Activity) : BaseRecyclerAdapter.ClickListener {

    var popupWindow: PopupWindow? = null
    private val view: View by lazy {
        View.inflate(activity, R.layout.choose_popup, null)
    }

    private val cloudAdapter: CloudAdapter by lazy {
        CloudAdapter(activity)
    }

    fun getPopup(tvConnectMethod: TextView?, cloudMap: MutableList<CloudBean>) {
        val deviceWidth = getDeviceWidth(activity)
        popupWindow = PopupWindow(deviceWidth * 2 / 3, WRAP_CONTENT)
        val rvCloud = view.findViewById<RecyclerView>(R.id.rvCloud)
        rvCloud?.adapter = cloudAdapter
        cloudAdapter.clickListener = this
        cloudAdapter.cloudMap = cloudMap
        popupWindow?.contentView = view
        popupWindow?.isFocusable = true
        popupWindow?.isOutsideTouchable = false
        popupWindow?.setBackgroundDrawable(UiTools.getDrawable(R.drawable.shape_dialog_bg))
        popupWindow?.showAsDropDown(tvConnectMethod, Gravity.CENTER, 0, 0)

    }

    interface ChooseCloud {
        fun onChooseCloud(cloudType: CloudBean, position: Int)
    }

    fun getCloudList(): MutableList<CloudBean> {
        return cloudAdapter.cloudMap
    }

    var chooseCloud: ChooseCloud? = null
    override fun clickListener(position: Int, view: View?) {
        val cloudMap = cloudAdapter.cloudMap
        if (popupWindow?.isShowing == true) {
            popupWindow?.dismiss()
        }
        chooseCloud?.onChooseCloud(cloudMap[position], position)
        cloudAdapter.notifyDataSetChanged()
    }

    override fun longClickListener(position: Int, view: View?): Boolean {
        return false
    }
}